package com.lujianfei.netease_android_canvas.ui

import android.animation.ValueAnimator
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.lujianfei.netease_android_canvas.R
import com.lujianfei.netease_android_canvas.utils.BezierUtils
import com.lujianfei.netease_android_canvas.utils.DensityUtils
import com.lujianfei.netease_android_canvas.widget.QuadBezierView

class BezierAnimExplainActivity : AppCompatActivity() {

    var view: View? = null
    var bezier: QuadBezierView? = null
    var objectAnimator: ValueAnimator? = null
    // 控制点 (0,0.9)，用于实现贝塞尔曲线的加速效果，两个的值范围[0,1]
    private val p1_x = 0f
    private val p1_y = 0.9f
    // 起点和终点
    private var startValue = 0f
    private var endValue = 0f
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_bezier_anim_explain)
        view = findViewById(R.id.view)
        bezier = findViewById(R.id.bezier)
        bezier?.setControlPoint(p1_x, p1_y)
        startValue = 0f
        endValue = DensityUtils.getScreenWidth(this) - DensityUtils.dip2px(this, 50f).toFloat()
        view?.let { viewNonNull ->
            objectAnimator = ValueAnimator.ofFloat(
                    startValue,
                    endValue)
            objectAnimator?.apply {
                duration = 2000
                repeatCount = ValueAnimator.INFINITE
                addUpdateListener {
                    val pos = (it.animatedValue as Float - startValue) / endValue // [0,1]
                    bezier?.setCurrentPos(pos)
                    // 根据 x 输入值 反算 t
                    val t = BezierUtils.getT(input = it.animatedValue as Float,
                            p0 = startValue,
                            p1 = p1_x * (endValue - startValue),
                            p2 = endValue)
                    // 通过变速的 t 算 y 的值，从而得到变速的 translationX
                    viewNonNull.translationX = BezierUtils.quadBezier(t,
                            p0 = startValue,
                            p1 = p1_y * (endValue - startValue),
                            p2 = endValue)
                }
                start()
            }
        }
        bezier?.apply {
            layoutParams.width = DensityUtils.getScreenWidth(this@BezierAnimExplainActivity)
            layoutParams.height = layoutParams.width
            layoutParams = layoutParams
        }
    }

    override fun onDestroy() {
        objectAnimator?.cancel()
        super.onDestroy()
    }
}
